<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\job\RechargeOrder;
use app\common\model\recharge\Config;
use app\common\model\recharge\Order;
use think\Db;

/**
 * 会员充值接口
 */
class Recharge extends Api
{
    protected $noNeedLogin = ['recharge_config'];
    protected $noNeedRight = ['*'];

    /**
     * 充值余额
     * @ApiMethod (get)
     * 
     */
    public function recharge_config()
    {
        $data = Config::all();
        $this->success('', $data);
    }
    /**
     * @Author LK
     * @date: 2023-10-31 
     * @ApiTitle (充值详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function recharge_info()
    {
        $id = request()->param('id');
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $info = Config::get($id);
        $this->success('', $info);
    }
    /**
     * @Author LK
     * @ApiTitle (充值)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="充值id")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function recharge()
    {
        $param = request()->param();
        extract($param);
        if (!config('site.reg_switch')) {
            $this->error('充值入口已关闭');
        }
        $config = Config::get($id);
        if (!$config) {
            $this->error('提交充值失败');
        }
        $data = [
            'orderid'   => sn('recharge_order', 'orderid', 'RZ'),
            'user_id'   => $this->auth->id,
            'pay_fee' => $config->recharge_price,
            'send_fee' => $config->send_price,
            'reg_id' => $id,
            'reg_info' => json_encode($config),
        ];
        Db::startTrans();
        try {
            $order = new Order($data);
            $order->allowField(true)->save();
            if ($order->id) {
                queue(RechargeOrder::class, $order->id, 600, 'rechargeOrder1276');
            } else {
                exception('充值下单失败');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('支付失败：' . $e->getMessage());
        }
        $this->success('', $order->id);
    }

    /**
     * @Author LK
     * @ApiTitle (充值记录)
     * @ApiMethod (get)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function logs()
    {
        $param = request()->param();
        extract($param);
        $lists = Order::with('user')->where('pay_status', '10')->where('user_id', $this->auth->id)->order('paytime desc')->paginate();
        $this->success('', $lists);
    }
}
